<?php
namespace classlib;
require 'database/parser.cls.php';
require 'database/query.cls.php';
use classlib\database\query;
class orm {
    const DT_SQL            = 'sql';
    const DT_AUTO           = 'auto';
    const DT_BINARY			= 'binary';
    
    const OP_AS             = 'AS';     
    const OP_MAX            = 'MAX';
    const OP_MIN            = 'MIN';
    const OP_SUM            = 'SUM';
    const OP_AVG            = 'AVG';
    const OP_COUNT          = 'COUNT';
    
    const OP_EQ             = '=';
    const OP_NE             = '<>';
    const OP_GT             = '>';
    const OP_LT             = '<';
    const OP_GE             = '>=';
    const OP_LE             = '<=';
    const OP_BETWEEN        = 'BETWEEN';
    const OP_LIKE           = 'LIKE';
	const OP_NOTLIKE        = 'NOT LIKE';
    const OP_REGEXP         = 'REGEXP';
    const OP_ISNULL         = 'IS NULL';
    const OP_ISNOTNULL      = 'IS NOT NULL';
    const OP_IN             = 'IN';
    const OP_NOTIN          = 'NOT IN';
    const OP_AND            = 'AND';
    const OP_OR             = 'OR';
    const OP_NOT            = 'NOT';
    const OP_SQL            = 'SQL';
    
    const FETCH_ASSOC       = 1;
    const FETCH_NUM         = 2;
    const FETCH_BOTH        = 3;
    const FETCH_OBJ         = 4;
    
    const ASC               = 'ASC';
    const DESC              = 'DESC';
    
    /**
     * 所有涉及数据的连接句柄都放置这里
     * @var query
     */
    static $query;
    
    /**
     * 创建一个数据库查询实例
     * @param  string $index db.main.reader 或者 db.main.writer
     * @param  string $pid 唯一编号用于做进程或者多线程实例化多个对象
     * @return query
     * @static 
     */
    public static function inst($db, $pid='') {
    	$skey = ($pid)? $db.$pid:$db;
    	if(!isset(self::$query[$skey])) {
    		$path   = str_replace('.', '/', $db);
    		$qkey   = basename($path);
    		$dbinc  = \classlib\core\config::load('db/'.dirname($path), false);
    		$args   = is_string($dbinc[$qkey])? $dbinc[$dbinc[$qkey]]:$dbinc[$qkey];
			$parser = '\classlib\database\\'.$args['params']['driver'];
	        $parser = new $parser($args['params'], $args['options']);
	        self::$query[$skey] = new query($parser);
    	}
        return self::$query[$skey];
    }
    
    /**
     * 关闭所有的连接句柄
     * @return void
     */
    public static function close() {
    	if (!empty(self::$query)) {
    		foreach (self::$query as $db) {
    			$db->get_parser()->close();
    		}
    	}
    }
}
